package com.fablesoft.projectdatacollect.ui.fragment;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.authentication.utils.ToastUtil;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseInfoNewBean;
import com.fablesoft.projectdatacollect.bean.BaseInfoResponse;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.DepartmentBean;
import com.fablesoft.projectdatacollect.bean.DepartmentListResponse;
import com.fablesoft.projectdatacollect.bean.EducationBean;
import com.fablesoft.projectdatacollect.bean.EducationListResponse;
import com.fablesoft.projectdatacollect.bean.PersonTypeBean;
import com.fablesoft.projectdatacollect.bean.PersonTypeListResponse;
import com.fablesoft.projectdatacollect.bean.PositionBean;
import com.fablesoft.projectdatacollect.bean.PositonListResponse;
import com.fablesoft.projectdatacollect.bean.TeamBean;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.DateUtil;
import com.fablesoft.projectdatacollect.util.Log4jUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FragmentBaseinfo<T> extends BaseFragment implements DialogFragmentBaseInfo.ItemCheckedListener, TextView.OnEditorActionListener {

    private TextView tvType;
    private TextView tvPost;
    private TextView tvDepartment;
    private TextView tvTime;
    private TextView tvEducation;
    private TextView tvTeam;
    private EditText etContact;
    private Button btNext3;
    private Button btLast3;

    private View vTeam;

    public List<DepartmentBean> departmentList = new ArrayList<>();
    public List<PositionBean> positionList = new ArrayList<>();
    public List<PersonTypeBean> personTypeList = new ArrayList<>();
    public List<EducationBean> educationList = new ArrayList<>();
    public List<TeamBean> teamList = new ArrayList<>();

    private String id;
    private String photoId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_base_info, container, false);
        initView();
        initData();
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        tvType = (TextView) view.findViewById(R.id.tv_type);
        tvPost = (TextView) view.findViewById(R.id.tv_post);
        tvDepartment = (TextView) view.findViewById(R.id.tv_department);
        tvTime = (TextView) view.findViewById(R.id.tv_time);
        tvEducation = (TextView) view.findViewById(R.id.tv_education);
        vTeam = view.findViewById(R.id.ll_team);
        tvTeam = (TextView) view.findViewById(R.id.tv_team);
        etContact = (EditText) view.findViewById(R.id.et_contact);
        btNext3 = (Button) view.findViewById(R.id.next3);
        btLast3 = (Button) view.findViewById(R.id.last3);
        btNext3.setOnClickListener(this);
        btLast3.setOnClickListener(this);
        tvDepartment.setOnClickListener(this);
        tvPost.setOnClickListener(this);
        tvType.setOnClickListener(this);
        tvEducation.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        tvTeam.setOnClickListener(this);
        etContact.setOnEditorActionListener(this);
        if (MyApplication.getInstance().getUserType().equals("3")){
            vTeam.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        initConstructionTeamData();
        initPositionData();
        if (!mActivity.result.getMessage().contains("人员已登记")) {
            if (TextUtils.isEmpty(mActivity.result.getCustomizePhotoId())) {
                photoId = mActivity.result.getPhotoId();
            } else {
                photoId = mActivity.result.getCustomizePhotoId();
            }
        }
        if (mActivity.result != null && mActivity.result.getData() != null && mActivity.result.getData().getOrgPersonBean() != null) {
            BaseInfoNewBean bean = mActivity.result.getData().getOrgPersonBean();
            tvType.setText(getPersonTypeName(bean.getType()));
            tvType.setTag(bean.getType());
            tvDepartment.setText(bean.getDepartmentName());
            tvDepartment.setTag(bean.getDepartmentCode());
            tvPost.setText(bean.getPostName());
            tvPost.setTag(bean.getPostCode());
            tvEducation.setText(bean.getDegreeName());
            tvEducation.setTag(bean.getDegree());
            tvTeam.setText(bean.getTeamName());
            tvTeam.setTag(bean.getTeam());
            etContact.setText(bean.getCellphone());
            if (bean.getInTime() != 0) {
                tvTime.setText(DateUtil.formatStrDate(bean.getInTime()));
            }
            id = bean.getId();
            photoId = bean.getPhotoId();
        }
        if (TextUtils.isEmpty(tvTime.getText())) {
            tvTime.setText(DateUtil.getCurrentDateStr());
        }
    }

    @Override
    public void onClick(View v) {
        if (isRepeatClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_department:
                showBaseInfoDialog((List<T>) departmentList, CommonUtils.FLAG_DEPARTMENT);
                break;
            case R.id.tv_post:
                showBaseInfoDialog((List<T>) positionList, CommonUtils.FLAG_POSITION);
                break;
            case R.id.tv_education:
                showBaseInfoDialog((List<T>) educationList, CommonUtils.FLAG_EDUCATION);
                break;
            case R.id.tv_type:
                showBaseInfoDialog((List<T>) personTypeList, CommonUtils.FLAG_PEOPLE_TYPE);
                break;
            case R.id.tv_team:
                showBaseInfoDialog((List<T>) teamList, CommonUtils.FLAG_TEAM);
                break;
            case R.id.tv_time:
                showDatePickerDialog();
                break;
            case R.id.next3:
                if (TextUtils.isEmpty(tvDepartment.getText())) {
                    ToastUtil.showToast(mContext, "请输入部门！");
                    return;
                }
                if (TextUtils.isEmpty(tvPost.getText())) {
                    ToastUtil.showToast(mContext, "请输入岗位！");
                    return;
                }
                if (TextUtils.isEmpty(tvType.getText())) {
                    ToastUtil.showToast(mContext, "请输入人员种类！");
                    return;
                }
                if (TextUtils.isEmpty(tvTime.getText())) {
                    ToastUtil.showToast(mContext, "请输入入场时间！");
                    return;
                }
                if (!TextUtils.isEmpty(etContact.getText().toString()) && !CommonUtils.checkIsPhone(etContact.getText().toString())) {
                    ToastUtil.showToast(mContext, "输入的手机号不合法！");
                    return;
                }
                listener.onNext(3);
                break;
            case R.id.last3:
                listener.onLast(3);
        }
    }

    private void showBaseInfoDialog(List<T> datas, int flag) {
        DialogFragmentBaseInfo dialog = new DialogFragmentBaseInfo();
        dialog.setItemCheckedListener(this);
        dialog.setDatas(datas, flag);
        dialog.show(getFragmentManager(), "base_info_dialog");
    }

    private void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                tvTime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @Override
    public void onChecked(int position, int flag) {
        Log.d("sglei-baseinfo", "position = " + position);
        if (flag == CommonUtils.FLAG_DEPARTMENT) {
            tvDepartment.setText(departmentList.get(position).getName());
            tvDepartment.setTag(departmentList.get(position).getCode());
        } else if (flag == CommonUtils.FLAG_PEOPLE_TYPE) {
            tvType.setText(personTypeList.get(position).getName());
            tvType.setTag(personTypeList.get(position).getValue());
        } else if (flag == CommonUtils.FLAG_EDUCATION) {
            tvEducation.setText(educationList.get(position).getName());
            tvEducation.setTag(educationList.get(position).getValue());
        } else if (flag == CommonUtils.FLAG_POSITION) {
            tvPost.setText(positionList.get(position).getName());
            tvPost.setTag(positionList.get(position).getCode());
        } else if (flag == CommonUtils.FLAG_TEAM){
            tvTeam.setText(teamList.get(position).getWorkTeamName());
            tvTeam.setTag(teamList.get(position).getId());
        }
    }

    public void submitBaseInfo() {
        Map<String, Object> param = new HashMap<>();
        param.put("id", TextUtils.isEmpty(id) ? "" : id);
        param.put("idNo", mActivity.idNo);
        param.put("photoId", photoId);
        param.put("cellphone", etContact.getText().toString());
        param.put("departmentCode", tvDepartment.getTag());
        param.put("inTime", DateUtil.str2Date(tvTime.getText().toString(), "yyyy-MM-dd"));
        param.put("orgId", MyApplication.getInstance().getOrgId());
        param.put("postCode", tvPost.getTag());
        param.put("degree", tvEducation.getTag());
        param.put("type", tvType.getTag());
        param.put("team", tvTeam.getTag());
        Log.d(CommonUtils.TAG_UPLOAD, "基本信息开始上传......param = " + param);
        HttpThread thread = new HttpThread(Config.UPLOAD_BASEINFO_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.UPLOAD_BASEINFO;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        mActivity.onNotLogin(response);
                    }
                }, param, BaseInfoResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(thread);
    }

    private String getPersonTypeName(String type) {
        for (PersonTypeBean person : personTypeList) {
            if (person.getValue().equals(type)) {
                return person.getName();
            }
        }
        return "";
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            CommonUtils.hideSoftKeyboard(mActivity);
            return true;
        }
        return false;
    }

    // 获取部门列表
    private void initConstructionTeamData() {
        Map<String, Object> mapParams = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgId", MyApplication.getInstance().getOrgId());
        mapParams.put("mapParams", params);
        HttpThread httpThread = new HttpThread(Config.CONSTRUCTION_TEAMS_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.GET_CONSTRUCTION_TEAMS_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                    }
                }, mapParams, DepartmentListResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    //获取岗位列表
    private void initPositionData() {
        Map<String, Object> mapParams = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgId", MyApplication.getInstance().getOrgId());
        mapParams.put("mapParams", params);
        HttpThread httpThread = new HttpThread(Config.GET_POSITION_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.GET_POSITION_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                    }
                }, mapParams, PositonListResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CommonUtils.GET_CONSTRUCTION_TEAMS_CODE:
                    if (msg.obj == null) {
                        return;
                    }
                    DepartmentListResponse departmentListResponse = (DepartmentListResponse) msg.obj;
                    if (departmentListResponse.getRows() != null) {
                        departmentList.addAll(departmentListResponse.getRows());
                    }
                    break;
                case CommonUtils.GET_POSITION_CODE:
                    if (msg.obj == null) {
                        return;
                    }
                    PositonListResponse positonListResponse = (PositonListResponse) msg.obj;
                    if (positonListResponse.getRows() != null) {
                        positionList.addAll(positonListResponse.getRows());
                    }
                    break;
                case CommonUtils.UPLOAD_BASEINFO:
                    BaseInfoResponse baseInfoResponse = (BaseInfoResponse) msg.obj;
                    if (baseInfoResponse == null) {
                        Toast.makeText(mContext,
                                R.string.request_error, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!baseInfoResponse.getSuccess()) {
                        Toast.makeText(mContext, baseInfoResponse.getMessage(), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mActivity.baseInfo = baseInfoResponse.getData();
                    listener.onSubmitOthers();
                    break;
            }
        }
    };
}
